<?php


namespace app\model;


use think\facade\Db;
use think\Model;
use utils\Define;

class Address extends Model
{


    /**
     * 列表
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function list($data)
    {
        $list = Db::name('address')->where(['user_id' => $data['user_id']])->paginate($data['limit'])->toArray();
        return app('json')->json_success('成功', $list);
    }


    /**
     * 地址操作
     * @param $data
     * @param $user
     * @return mixed
     */
    public function modify($data, $user)
    {
        Db::startTrans();
        try {
            switch ($data['type']) {
                case 1:
                    if ($data['is_default'] == 1) {
                        //修改其他默认的数据
                        $this->where(['user_id' => $data['user_id']])->update(['is_default' => 0]);
                    }
                    $this->replace()->save($data);
                    //查看用户是否绑定地址并且没有得到过奖励
                    $log = Db::name('money_log')->where(['user_id' => $data['user_id'], 'type' => 4])->count();
                    if ($log <= 0 && $user->is_real_name == 1) {
                        MoneyLog::SetUserMoney($data['user_id'], $user->integral, SystemConfig('real_name'), 4);
                        $user->integral += SystemConfig('real_name');
                        $user->save($data);
                    }
                    break;
                case 2:
                    if ($data['is_default'] == 1) {
                        //修改其他默认的数据
                        $this->where(['user_id' => $data['user_id']])->update(['is_default' => 0]);
                    }
                    $this->replace()->save($data);
                    break;
                default:
                    $this->where(['id' => $data])->delete();
                    break;
            }
            Db::commit();
            return app('json')->json_success('成功');
        } catch (\Exception $exception) {
            Db::rollback();
            return app('json')->json_error('失败');
        }
    }
}